﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
using System.IO.Ports;

namespace CardMonitor.Utils
{
    public class ICWriter
    {
        private SerialPort _serialPort;

        public ICWriter(string comPort = "COM3", int baudRate = 9600)
        {
            _serialPort = new SerialPort(comPort, baudRate)
            {
                ReadTimeout = 5000,
                WriteTimeout = 5000
            };
        }

        // 检测IC卡类型（命令格式：50H 30H）
        public string DetectCardType()
        {
            byte[] cmd = { 0x50, 0x30 };
            byte[] response = SendCommand(cmd);

            // 解析响应（示例逻辑，需根据实际协议调整）
            if (response.Length >= 2 && response[0] == 0x90 && response[1] == 0x00)
            {
                return "CPU Card (T=0/T=1)";
            }
            else if (response.Length >= 2 && response[0] == 0x53 && response[1] == 0x00)
            {
                return "SLE4442/SLE4428 Card";
            }
            return "Unknown Card";
        }

        // CPU卡写数据示例（使用APDU命令）
        public bool WriteToCpuCard(byte[] data)
        {
            try
            {
                // 1. 激活卡片（命令：51H 30H）
                SendCommand(new byte[] { 0x51, 0x30 });

                // 2. 构建APDU写命令（示例：更新二进制命令）
                byte[] apdu = new byte[5 + data.Length];
                apdu[0] = 0x00; // CLA
                apdu[1] = 0xD6; // INS (UPDATE BINARY)
                apdu[2] = 0x00; // P1 (高位地址)
                apdu[3] = 0x00; // P2 (低位地址)
                apdu[4] = (byte)data.Length; // Lc
                Array.Copy(data, 0, apdu, 5, data.Length);

                // 3. 发送APDU命令（命令：51H 33H + APDU）
                byte[] fullCmd = new byte[apdu.Length + 2];
                fullCmd[0] = 0x51;
                fullCmd[1] = 0x33;
                Array.Copy(apdu, 0, fullCmd, 2, apdu.Length);

                byte[] response = SendCommand(fullCmd);
                return CheckSuccess(response);
            }
            finally
            {
                SendCommand(new byte[] { 0x51, 0x31 }); // 下电
            }
        }

        // SLE4442卡写数据示例
        public bool WriteToSLE4442(byte[] data, byte[] password)
        {
            try
            {
                // 1. 激活卡片（命令：53H 30H）
                SendCommand(new byte[] { 0x53, 0x30 });

                // 2. 校验密码（命令：53H 33H 00H 20H 03H + 密码）
                byte[] verifyCmd = { 0x53, 0x33, 0x00, 0x20, 0x03 };
                byte[] fullVerifyCmd = new byte[verifyCmd.Length + password.Length];
                Array.Copy(verifyCmd, fullVerifyCmd, verifyCmd.Length);
                Array.Copy(password, 0, fullVerifyCmd, verifyCmd.Length, password.Length);

                if (!CheckSuccess(SendCommand(fullVerifyCmd)))
                    throw new Exception("密码验证失败");

                // 3. 写入主存储区（命令：53H 33H 地址高位 地址低位 长度 + 数据）
                byte[] writeCmd = { 0x53, 0x33, 0x00, 0x00, (byte)data.Length };
                byte[] fullWriteCmd = new byte[writeCmd.Length + data.Length];
                Array.Copy(writeCmd, fullWriteCmd, writeCmd.Length);
                Array.Copy(data, 0, fullWriteCmd, writeCmd.Length, data.Length);

                byte[] response = SendCommand(fullWriteCmd);
                return CheckSuccess(response);
            }
            finally
            {
                SendCommand(new byte[] { 0x53, 0x31 }); // 下电
            }
        }

        private byte[] SendCommand(byte[] command)
        {
            if (!_serialPort.IsOpen)
                _serialPort.Open();

            _serialPort.Write(command, 0, command.Length);

            // 读取响应（需要根据实际协议确定响应长度）
            byte[] buffer = new byte[256];
            int bytesRead = _serialPort.Read(buffer, 0, buffer.Length);
            byte[] response = new byte[bytesRead];
            Array.Copy(buffer, response, bytesRead);
            return response;
        }

        public void ceshi()
        {
            var writer = new ICWriter("COM8");

            try
            {
                string cardType = writer.DetectCardType();
                Console.WriteLine($"检测到卡类型：{cardType}");

                byte[] dataToWrite = { 0x01, 0x02, 0x03, 0x04 };

                if (cardType.Contains("CPU"))
                {
                    if (writer.WriteToCpuCard(dataToWrite))
                        Console.WriteLine("CPU卡写入成功");
                }
                else if (cardType.Contains("SLE4442"))
                {
                    byte[] password = { 0xFF, 0xFF, 0xFF }; // 默认密码
                    if (writer.WriteToSLE4442(dataToWrite, password))
                        Console.WriteLine("SLE4442卡写入成功");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"操作失败：{ex.Message}");
            }
        }


        private bool CheckSuccess(byte[] response)
        {
            // 成功响应通常为 90 00
            return response.Length >= 2 &&
        response[response.Length - 2] == 0x90 &&  // 倒数第二个元素
        response[response.Length - 1] == 0x00;    // 最后一个元素
        }
    }

  
   
}
